/*
 * @(#)HanQDiskLinks.java $version 2012-3-26
 * 
 * Copyright 2011 RogueDevelopment Gruop. All rights Reserved.
 * ROGUEDEVELOPMENT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nadostar.extensions.jsoup.impl;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.nadostar.extensions.jsoup.ListLinks;
import com.nadostar.extensions.jsoup.TargetMovieInfo;
import com.nadostar.extensions.jsoup.TargetMovieLink;

/**
 * @author LEESUNG
 *
 */
public class HanQDiskLinks implements ListLinks {
	private static Log log = LogFactory.getLog(HanQDiskLinks.class);
	
	public TargetMovieInfo getMargetMovieInfo(String url) throws IOException {
		TargetMovieInfo movieInfo = new TargetMovieInfo();
		
		movieInfo.setUrl(url);
		log.debug("Fetching ..." + url);

		Document doc = Jsoup.connect(url).get();
		
		log.debug("Title ..." + doc.select("table.vod_list_top").select("tr td:eq(0)").text() + "\n");
		
		Element vod_list = doc.getElementById("video_list");
		Elements childTrElement = vod_list.getElementsByTag("tr");
		
		List<TargetMovieLink> targetLinkList = new ArrayList<TargetMovieLink>();
		for(Element el : childTrElement) {
			
			String subTitle = el.select("td:eq(1)").text();
			String ylink = el.select("td:eq(2)").select("img").attr("onclick");
			String tlink = el.select("td:eq(3)").select("a").attr("onclick");
			if(ylink.length() > 0) {
				if(ylink.indexOf(",") > 0) {
					ylink = URLDecoder.decode(ylink.split(",")[0].replace("player(\'", "").replace("\'", ""), "UTF-8");
				}
			}
			
			if(tlink.length() > 0) {
				if(tlink.indexOf(",") > 0) {
					tlink = URLDecoder.decode(tlink.split(",")[0].replace("playerTwoddo(\'", "").replace("\'", ""), "UTF-8");
				}
			}
			
			if(subTitle.length() > 0) {
				
				log.debug("TITLE: " + subTitle);
				log.debug("YOUKU: " + URLDecoder.decode(ylink, "UTF-8"));
				log.debug("TUDOU: " + URLDecoder.decode(tlink, "UTF-8"));
				log.debug("\n");
				
				TargetMovieLink movieLink = new TargetMovieLink();
				movieLink.setTitle(subTitle);
				movieLink.setLink(URLDecoder.decode(tlink, "UTF-8").length() > 0 ? URLDecoder.decode(tlink, "UTF-8") : URLDecoder.decode(ylink, "UTF-8"));
				movieLink.setLink2(URLDecoder.decode(ylink, "UTF-8"));
				
				targetLinkList.add(movieLink);
			}
		}
		
		movieInfo.setLinks(targetLinkList);
		
		return movieInfo;
	}

}
